package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        // 获取上传的文件名
        String originalFilename = file.getOriginalFilename();
        // 获取后缀名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新的文件名
        String fileName = UUID.randomUUID().toString() + ext;
        // 创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }

        File targetFile = new File(path, fileName);

        file.transferTo(targetFile);
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        File origFile = new File(path, name);
        // 获取文件输入流
        FileInputStream fileInputStream = new FileInputStream(origFile);
        // 获取浏览器输出流
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buf= new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        fileInputStream.close();

    }
}
